#!/bin/sh

DIR="/root/openvpn/ovpn-data"
NAME="openvpn"
PORT=5003
DSTIP=liuchenxi.love

function main {
        case $1 in 
                "setup")
                        rm ${DIR} -rf
                        mkdir -p ${DIR}
                        docker run -v ${DIR}:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u udp://${DSTIP}
                        docker run -v ${DIR}:/etc/openvpn --rm -it kylemanna/openvpn ovpn_initpki
                        sed "s/port .*/port ${PORT}/" -i ${DIR}/openvpn.conf
                        sed "s/declare -x OVPN_PORT=/declare -x OVPN_PORT=${PORT}/" -i ${DIR}/ovpn_env.sh
                return
                ;;
                "run")
                        docker stop ${NAME} >/dev/null 2>&1
                        docker rm ${NAME} >/dev/null 2>&1
                        sed "s/port .*/port ${PORT}/" -i ${DIR}/openvpn.conf
                        sed "s/declare -x OVPN_PORT=.*/declare -x OVPN_PORT=${PORT}/" -i ${DIR}/ovpn_env.sh
                        docker run --name ${NAME} -v ${DIR}:/etc/openvpn -d -p ${PORT}:${PORT}/udp --cap-add=NET_ADMIN kylemanna/openvpn
                return
                ;;
                "product")
                        docker run -v ${DIR}:/etc/openvpn --rm -it kylemanna/openvpn easyrsa build-client-full $2 nopass
                        docker run -v ${DIR}:/etc/openvpn --rm kylemanna/openvpn ovpn_getclient $2> $2.ovpn
                return
                ;;
                "log")
                        docker exec ${NAME} cat /tmp/openvpn-status.log
                        return
                ;;
        esac

        echo "err cmd $1"
}

main $*